/**
 * center 项目 vue全局插件
 * 2017年7月30日 星期日
 * Joshua Coenro
 */
import SuRong from "./config.surong.js"
import Axios from 'axios'

// Windows 全局变量
// 引入编译信息
//require('./compile')
import Compile from './compile'
window.SrCenter = Compile
window.Axios = Axios

export default{
    install(Vue){
        // 私有数据
        var privateData = {};
        // 全局帮助函数
        class Susanna{
            constructor(){}
            static base64_decode(encodeStr){
                return new Buffer(encodeStr, 'base64').toString('base64')
            }
            static base64_encode(Str){
                return new Buffer(Str).toString('base64')
            }
            /**
             * @param {object|Array} json 
             * @return {bool}
             */
            static EmptyJson(json){
                var isEmpty = true
                if('object' == typeof json){
                    if(json instanceof Array){
                        if(json.length > 0) isEmpty = false
                    }
                    else{
                        for(var k in json){
                            isEmpty = false
                            break
                        }
                    }
                }
                return isEmpty
            }
            /**
             * 字符串渲染
             * @static
             * @param {string} str  字符串
             * @param {fucntion} callback 
             * @returns {string}
             * @memberof Susanna
             */
            static render(str, callback){
                var reg = /\{[^\}]+\}/g
                var matchList = str.match(reg)
                if(matchList){
                    callback = 'function' == typeof callback? callback: null
                    for(var i=0; i<matchList.length; i++){
                        var key = matchList[i]
                        if(callback){
                            var value = callback(key.replace(/\{|\}/g, ''))
                            value = value || ''
                            str  = str.replace(new RegExp(key, 'g'), value)
                        }
                    }
                }
                return str
            }
        }
        // 储存器
        class SusannaStorage{
            /**
             * @param {string|null} ns 命名空间，为空时值全局变量
             * @param {string} dirver SESSION/LOCAL
             * @param {bool} noDecode 不进行base64 编码
             */
            constructor(ns, dirver, noDecode){
                this.dirver = dirver || 'session'
                if(this.dirver) this.dirver = this.dirver.toUpperCase()
                this.ns = ns || null
                this.noDecode = noDecode || true

                // 值获取       
                this.rawJson = this.GetRawJson()
            }
            /**
             * @param {string} key 
             * @param {any} def 
             */
            Get(key, def){
                def = def || null
                if(this.ns){
                    return key? this.rawJson[key] || def : this.rawJson
                }
                return (('SESSION' == this.dirver)? sessionStorage.getItem(key): localStorage.getItem(key)) || def
            }
            hasKey(key){
            }
            /**
             * 链式后去值
             * @param {string} key 
             * @param {function} callback 
             * @return {SusannaStorage}
             */
            GetCallback(key, callback){
                if(key){
                    var value = this.Get(key, false)
                    if(false !== value && 'function' == typeof callback){
                        callback(value)
                    }
                }
                return this
            }
            /**
             * 设置值，可作为链式调用
             * @param {string} key 
             * @param {any} value 
             * @param {bool} commit 
             * @return {SusannaStorage}
             */
            Set(key, value, commit){
                var json = ('object' == typeof key)? key: null
                if(null === json){
                    json = {}
                    json[key] = value
                }
                this.rawJson = Object.assign(this.rawJson, json)
                if(commit){
                    this.Save()
                }
                return this
            }
            /**
             * 删除数据
             * @param {string|Array} keys 
             * @param {bool} commit
             * @return {SusannaStorage}
             */
            Del(keys, commit){
                keys = 'object' == typeof keys? keys : [keys]
                for(var i=0; i<keys.length; i++){
                    delete this.rawJson[keys[i]]
                }
                if(commit){
                    this.Save()
                }
                return this
            }
            /**
             * 获取原始的json值
             * @return {Object}
             */
            GetRawJson(){
                var json = {}
                if(this.ns){
                    if('SESSION' == this.dirver){
                        var value = sessionStorage.getItem(this.ns)
                        if(value){
                            if(!this.noDecode){
                                json = Susanna.base64_decode(value)
                            }
                            json = JSON.parse(value)
                        }
                    }else{
                        var value = sessionStorage.getItem(this.ns)
                        if(value){
                            if(!this.noDecode){
                                json = Susanna.base64_decode(value)
                            }
                            json = JSON.parse(value)
                        }
                    }
                }
                return json
            }
            /**
             * 数据保存
             * @return {bool}
             */
            Save(){
                if(!Susanna.EmptyJson(this.rawJson)){
                    // console.log(this.rawJson)
                    if(this.ns){
                        var value = JSON.stringify(this.rawJson)
                        if(!this.noDecode){
                            value = Susanna.base64_encode(value)
                        }
                        if('SESSION' == this.dirver){
                            return sessionStorage.setItem(this.ns, value)
                        }else{
                            return localStorage.setItem(this.ns, value)
                        }
                        
                    }
                    else{
                        for(var k in this.rawJson){
                            if('SESSION' == this.dirver){
                                return sessionStorage.setItem(k, this.rawJson[k])
                            }else{
                                return localStorage.setItem(k, this.rawJson[k])
                            }
                        }
                    }
                }
                return false
            }
        }
        // pigeons 库
        class pigeons{
            /**
             * 
             * @param {object|null} opts 
             */
            constructor(opts){
                this.option = opts || {};                
            }
            /**
             * 获取基本的地址
             * @param {string} url 
             * @return {string}
             */
            getUrl(url){
                return (this.option['pref'] || '') + url;
            }
        }
        
        // 全局变量
        function C(){
            this.project_url = '/aurora/';  // 项目url
            this.baseurl = '/';      // 当前项目的基础地址
            this.baseimg = '/public/img/';      // 当前项目的基础地址
            this.token = false;
            this.surong = SuRong;   // 配置信息
        }
        var __sysStorage = new SusannaStorage('__sys__');
// ajax 请求封装 -----------------------------------------BEGIN
        /**
         * 
         * @param {JOSN} options {method}
         * @memberof Uymas
         */
        C.prototype.ajax = function(options){
            var xtq = new XMLHttpRequest();
            if(!options.load){
                options.load = function(){};
            }
            if(!options.error){
                options.error = function(){};
            }
            xtq.addEventListener('load', options.load);
            xtq.addEventListener('error', options.error);
            var url = options.url;
            xtq.open(options.method, url);

            // 设置头部
            if(options.headers){
                for(var headerKey in options.headers){
                    xtq.setRequestHeader(headerKey, options.headers[headerKey]);
                }
            }
            // xtq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            // xtq.setRequestHeader('Content-Type', 'multipart/form-data');
            // xtq.setRequestHeader('Access-Control-Allow-Origin', '*');
            // xtq.setRequestHeader('Content-Type', 'text/plain');
            xtq.send();
            return xtq;
        }
        /**
         * @param {string} url
         * @param {JSON} iptOption
         * @return {Promise}
         */
        C.prototype.get = function(url, iptOption){
            var $instance = this;
            var client;
            return new Promise(function(resolve, reject){
                var options = {
                    method: 'get',
                    url: url,
                    load: function(){
                        // console.log(client.getResponseHeader("Content-Type"));
                        var ContentType = this.getResponseHeader("Content-Type");
                        var result = {};
                        result.reponse = this;
                        if(ContentType.indexOf('application/json') > -1){
                            result.body = JSON.parse(this.response);
                        }
                        // console.log(ContentType, this.getAllResponseHeaders());
                        // console.log(this.getAllResponseHeaders());
                        resolve(result);
                    },
                    error: function(){
                        reject(this);
                    }
                }; 
                if(iptOption) options = Object.assign(options, iptOption);
                // console.log(iptOption);
                client = $instance.ajax(options);
            });
        }
        /**
         * @param {string} url
         * @param {JSON} data
         * @return {Promise}
         */
        C.prototype.post = function(url, data){
            var $instance = this;
            return new Promise(function(resolve, reject){
                var options = {
                    method: 'post',
                    url: url,
                    load: function(){
                        resolve(this);
                    },
                    error: function(){
                        reject(this);
                    }
                }; 
                $instance.ajax(options);
            });
        }
        /**
         * url get 参数解析
         * @param {string|null} sKey 
         * @param {any} def
         * @returns {string|Object}
         */
        C.prototype.getQuery = function(sKey, def){
            var href = location.href;
            var queryData = {};
            var idx;
            if((idx = href.indexOf('?')) > -1){
                href = href.substr(idx+1);
                var hashIdx;
                if((hashIdx = href.indexOf('#'))>-1){
                    href = href.substr(0, hashIdx);
                }
                var uQueue = href.split('&');
                for(var i=0; i<uQueue.length; i++){
                    var str = uQueue[i];
                    var idxKey = str.indexOf('=');
                    var key = str.substr(0, idxKey);
                    // url 解码
                    try {
                        queryData[key] = decodeURI(str.substr(idxKey+1))
                        // console.log(decodeURI(encoded));
                        // expected output: "https://mozilla.org/?x=шеллы""
                      } catch(e) { // catches a malformed URI
                        // console.error(e);
                        queryData[key] = str.substr(idxKey+1);
                      }
                }
            }
            def = def? def : false;
            if(sKey){
                return queryData[sKey] || def;
            }
            return queryData;
        }
// ajax 请求封装 -----------------------------------------END

        /**
         * @param {string} key 键名
         * @param {string} def 为空时默认值
         */
        C.prototype.getJsVar = function(key, def){
            def = def ? def:'';
            if(window._Aurora){
                return _Aurora[key]? _Aurora[key]:def;
            }
            return def;
        };
        // 获取地址
        C.prototype.url = function(url,type){return ('img' == type)? this.baseimg : this.baseurl + url;}
        // api地址
        C.prototype.ApiUrl = function(url){return this.project_url + 'api/' + url;}
        /**
         * @param {string} key 键值
         * @param {any} value 设置值
         * @param {any} def 默认
         */
        C.prototype.value = function(key,value,def){
            if('undefined' == typeof value || null === value){
                def = def? def:'';
                return privateData[key]? privateData[key]: def;
            }else privateData[key] = value;
        }
        /**
         * @param {function|object} any 注册函数或者对象
         */
        C.prototype.register = function(any,ns){            
            if('function' == typeof any) this.$App = new any(this);
            else this.$App = any;
        }
        /**
         * @param 格式化日期(中国话日期)
         */
        C.prototype.cndate = function(){
            var dt = new Date();
            return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
        }
        /**
         * @param {object} opt
         * @return {pigeons}
         */
        C.prototype.pigeons = function(opt){
            return new pigeons(opt);
        }
        /**
         * 获取 Pigeons 项目URL
         * @param {string} url
         * @return {string}
         */
        C.prototype.pigeonsUrl = function(url){
            return SuRong.pigeons.pref + url;
        }
        /**
         * pigeons/get 方式请求数据
         * @param {string} url
         * @param {JSON} args
         * @param {function} successHandler (data) 成功时
         * @param {function} errorHandler (msg, httpErrormk) 错误发生是， httpErrormk 表示网络原因
         * @param {function} whenLoadHandler 请求加载以后
         */
        C.prototype.PigeonsGet = function(url, args, successHandler, errorHandler, whenLoadHandler){
            if('function' != typeof successHandler){
                successHandler = (data) =>{};
            }
            if('function' != typeof errorHandler){
                errorHandler = (msg, httpErrormk) =>{};
            }
            var senddata = {
                key : url
            };
            if(args){
                senddata['args'] = args;
            }
            // console.log(SuRong)
            // https 模式
            if('SURONG' == SuRong.pigeons.mode){
                var $instance = this;
                url = Susanna.render(url, (v) => {
                    let retval = null;
                    if('user' == v){
                        retval = $instance.getJsVar('user')
                    }
                    return retval;
                });
                var sendheaderData = {};
                $instance.getSysPid((pid, token) =>{
                    sendheaderData = {'Conero-Pid': pid, 'Conero-Token': token};
                    if('development' == SuRong.pigeons.env){
                        sendheaderData['Conero-Type'] = 'No-Exception-Lad';
                    }
                    // $instance.get(SuRong.pigeons.pref + url, {params: args, headers: sendheaderData})
                    // .then(function(d){
                    //     var rps = d.response;
                    //     // console.log(d);
                    // })
                    // .catch(function(d){
                    //     // console.log(d);
                    // });
                    
                    // return;
                    Axios.get(SuRong.pigeons.pref + url, {method:'GET', params: args, headers: sendheaderData})
                    .then(function(d){
                        if('function' == typeof whenLoadHandler){
                            whenLoadHandler();
                        }
                        var data = d.data;                        
                        if(data.code == 400){
                            errorHandler(data.msg, false);
                        }else{
                            successHandler(data);
                        }
                    }).catch(function(error){
                        // 编辑模式自动删除 console.log 代码
                        // 语言级别错误，也会触发 catch
                        console.log(error)
                        errorHandler(error, true);
                    });
                })
            }
            else{
                Axios.get('/bin/pigeons', {params : senddata, headers: {'X-CSRF-TOKEN': __CENTER.csrf}}).then(function(d){
                    if('function' == typeof whenLoadHandler){
                        whenLoadHandler();
                    }
                    var data = d.data;
                    if(data.error){
                        errorHandler(data.msg, false);
                    }else{
                        successHandler(data.data);
                    }
                }).catch(function(error){
                    errorHandler(error, true);
                });
            }
        }
        /**
         * pigeons/get 方式请求数据
         * @param {string} url
         * @param {JSON} args
         * @param {function} successHandler (data) 成功时
         * @param {function} errorHandler (msg, httpErrormk) 错误发生是， httpErrormk 表示网络原因
         * @param {function} whenLoadHandler 请求加载以后
         */
        C.prototype.PigeonsPost = function(url, args, successHandler, errorHandler, whenLoadHandler){
            if('function' != typeof successHandler){
                successHandler = (data) =>{};
            }
            if('function' != typeof errorHandler){
                errorHandler = (msg, httpErrormk) =>{};
            }
            var senddata = {
                key : url
            };
            if(args){
                senddata['args'] = args;
            }
            // https 模式
            if('SURONG' == SuRong.pigeons.mode){
                var $instance = this;
                url = Susanna.render(url, (v) => {
                    let retval = null;
                    if('user' == v){
                        retval = $instance.getJsVar('user');
                    }
                    return retval;
                });
                $instance.getSysPid((pid, token) =>{
                    // console.log(args, typeof(args));
                    var postParam = new URLSearchParams();
                    for(var k in args){
                       if(null !== args[k]){
                           postParam.append(k, args[k]);
                       }
                    }
                    var sendheaderData = {
                        'Conero-Pid': pid, 
                        'Conero-Token': token,
                        // post 发送数据时
                        'Content-Type': 'application/x-www-form-urlencoded'
                    };
                    if('development' == SuRong.pigeons.env){
                        sendheaderData['Conero-Type'] = 'No-Exception-Lad';
                    }
                    Axios.post(SuRong.pigeons.pref + url, postParam , {
                        headers: sendheaderData
                    })
                    .then(function(d){
                        if('function' == typeof whenLoadHandler){
                            whenLoadHandler();
                        }
                        var data = d.data;                        
                        if(data.code == 400){
                            errorHandler(data.msg, false);
                        }else{
                            successHandler(data);
                        }
                    }).catch(function(error){
                        // 编辑模式自动删除 console.log 代码
                        // 语言级别错误，也会触发 catch
                        console.log(error)
                        errorHandler(error, true);
                    });
                })
            }else{
                Axios.post('/bin/pigeons', senddata, {headers: {'X-CSRF-TOKEN': __CENTER.csrf}}).then(function(d){
                    if('function' == typeof whenLoadHandler){
                        whenLoadHandler();
                    }
                    var data = d.data;
                    if(data.error){
                        errorHandler(data.msg, false);
                    }else{
                        successHandler(data.data);
                    }
                }).catch(function(error){
                    errorHandler(error, true);
                });
            }
        }
        /**
         * 系统当前登录用户的token值， js 请求方法,
         * @param {function} callback 回调函数
         */
        C.prototype.getLoginUserToken = function(callback){
            var token = __sysStorage.Get('__user_token');
            var tokendt = __sysStorage.Get('__user_token_dt');
            // 客服端缓存的用户代码
            var sUser = __sysStorage.Get('__user');
            var $instance = this;
            if(token && tokendt != $instance.cndate()){
                token = null;
            }
            // 不同用户时删除缓存
            if(token && sUser != _Aurora.user){
                token = null;
            }
            if(!token){
                var url = this.baseurl + 'bin/get_token';
                Axios.get(url)
                    .then((rs) =>{
                        var data = rs.data;
                        if(data.error){
                            // console.log(data);
                        }else{
                            __sysStorage.Set('__user_token', data.token)
                                    .Set('__user', _Aurora.user)
                                    .Set('__user_token_dt', $instance.cndate(), true);
                            $instance.token = data.token;
                            if($instance.token && 'function' == typeof callback){
                                return callback($instance.token);
                            }
                        }
                    })
                    //.catch()
                ;
            }else{
                $instance.token = token;
                if($instance.token && 'function' == typeof callback){
                    return callback($instance.token);
                }
            }
        }
        /**
         * 获取系统pid
         * @param {function} callback 回调函数 (pid, token)=>
         */
        C.prototype.getSysPid = function(callback){
            var spid = __sysStorage.Get('__sys_pid');
            var tokendt = __sysStorage.Get('__user_token_dt');   
            // 客服端缓存的用户代码
            var sUser = __sysStorage.Get('__user');
            var $instance = this;
            if(spid && (tokendt != $instance.cndate() || SuRong.pigeons.tokenCache)){
                spid = null;
            }         
            // 不同用户时删除缓存
            if(spid && sUser != _Aurora.user){
                spid = null;
            }       
            if(!spid){
                $instance.getLoginUserToken((token)=>{
                    var url = $instance.baseurl + 'bin/get_pid?token='+token;
                    Axios.get(url)
                        .then((rs) =>{
                            var data = rs.data;
                            if(data.error){
                            }else{
                                spid = data.pid;
                                __sysStorage.Set('__sys_pid', spid, true);
                                if(spid && 'function' == typeof callback){
                                    return callback(spid, token);
                                }
                            }
                        })
                    ;
                });
            }else{
                if(spid && 'function' == typeof callback){
                    return callback(spid, __sysStorage.Get('__user_token'));
                }
            }
        }
        /**
         * @return {SusannaStorage}
         */
        C.prototype.storage = function(ns, dirver, noDecode){
            return new SusannaStorage(ns, dirver, noDecode);
        }        
        Vue.prototype.$c = new C();
    }
}